package jianzhi_offer;

import java.util.ArrayList;
import java.util.PriorityQueue;

public class _28_最小的K个数 {
    public static void main(String[] args) {
        _28_最小的K个数 test = new _28_最小的K个数();
        Object obg = test.GetLeastNumbers_Solution(new int[]{4,5,1,6,2,7,3,8},4);
    }

    public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
        if(k > input.length || k <= 0) return new ArrayList<Integer>();
        PriorityQueue<Integer> heap = new PriorityQueue<Integer>(k,(o1,o2)->o2-o1);//最大堆
        for(int i=0;i<k;++i){
            heap.offer(input[i]);
        }
        for(int i=k;i<input.length;++i){
            if(input[i] < heap.peek()){
                heap.poll();
                heap.offer(input[i]);
            }
        }
        ArrayList<Integer> res = new ArrayList<Integer>(k);
        for(int i=0;i<k;++i) res.add(0);
        for(int i=k-1;i>=0;--i){
            res.set(i,heap.poll());
        }
        return res;
    }
}
